package com.zjk.toolkit.governance.service.impl;

import com.google.common.util.concurrent.RateLimiter;
import com.zjk.toolkit.governance.annotations.DoRateLimiter;
import com.zjk.toolkit.governance.config.Constant;
import com.zjk.toolkit.governance.service.IGovernanceService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class RateLimiterServiceImpl implements IGovernanceService {
    @Override
    public Object access(ProceedingJoinPoint joinPoint, Method method, Annotation annotation, Object[] args) throws Throwable {
        if (annotation instanceof DoRateLimiter && ((DoRateLimiter) annotation).limitPerSec()>0) {
            String clazz = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            String key = clazz + "." + methodName;
            if (Constant.RATE_LIMITER_CACHE.get(key) == null) {
                Constant.RATE_LIMITER_CACHE.put(key, RateLimiter.create(((DoRateLimiter) annotation).limitPerSec()));
            }
            RateLimiter rateLimiter = Constant.RATE_LIMITER_CACHE.get(key);
            if (rateLimiter.tryAcquire()) {
                return joinPoint.proceed();
            }
        }
        return null;
    }
}
